import { routerRedux } from 'dva/router';
import Router from 'umi/router';
import { stringify } from 'querystring';
import { fakeAccountLogin, getFakeCaptcha } from '@/services/login';
import { setAuthority } from '@/utils/authority';
import { getPageQuery } from '@/utils/utils';
import {getSystemMenu} from "@/services/user";
const Model = {
  namespace: 'login',
  state: {
    status: undefined,
  },
  effects: {
    *login({ payload }, { call, put }) {
      const response = yield call(fakeAccountLogin, payload);


      yield put({
        type: 'changeLoginStatus',
        payload: response,
      }); // Login successfully

      if (response.retCode === '0') {
        sessionStorage.setItem('idToken',response.data.idToken);
        localStorage.setItem('antd-pro-authority',JSON.stringify(response.data.userVO));
        // //根据不同权限跳转不用的页面
        const res = yield call(getSystemMenu);
        let buttonList=res.data.buttonList ||'';
        sessionStorage.setItem('buttonList',buttonList);
        let router = buttonList && buttonList.indexOf('model') !== -1 ? '/algorithm' : '/resource'
        router = router + (router === '/algorithm' ? (buttonList && buttonList.indexOf('data_center') !== -1 ? '/dataCenter' : '/modelCenter')
          : (buttonList && buttonList.indexOf('word_library') !== -1 ? '/dictionary' : '/vector'))
        yield put( routerRedux.push(router) );
        // yield put( routerRedux.push('/algorithm/dataCenter') );
      }
    },

    *getCaptcha({ payload }, { call }) {
      yield call(getFakeCaptcha, payload);
    },

    *logout(_, { put }) {
      const { redirect } = getPageQuery(); // redirect

      if (window.location.pathname !== '/user/login' && !redirect) {
        yield put(
          routerRedux.replace({
            pathname: '/user/login',
            search: stringify({
              redirect: window.location.href,
            }),
          }),
        );
      }
    },
  },
  reducers: {
    changeLoginStatus(state, { payload }) {
      setAuthority(payload.currentAuthority);
      return { ...state, status: payload.status, type: payload.type };
    },
  },
};
export default Model;
